#coding=utf-8

from urllib3.request import urlencode
from urllib.request import urlopen
import json

def get_location(name):
    params = {
        's': 'rsv3',
        'key': '8325164e247e15eea68b59e89200988b',
        'page': 1,
        'offset': 10,
        'city': 330100,
        'language': 'zh_cn',
        'callback': 'jsonp_643264_',
        'platform': 'JS',
        'logversion': 2.0,
        'sdkversion': 1.3,
        'appname': 'http://lbs.amap.com/console/show/picker',
        'csid': '401848AE-10D1-4E6C-A6F8-8494B9A42F68',
        'keywords': name,
    }

    try:
        path = 'http://restapi.amap.com/v3/place/text?' + urlencode(params)
        # print(path)
        u = urlopen(path)
        ret_data = u.read().decode().replace('jsonp_643264_(', '')[:-1]
        # print(ret_data)
        ret_obj = json.loads(ret_data)
        # print(ret_obj)
        if (len(ret_obj['pois']) > 0):
            location = ret_obj['pois'][0]['location'].split(',')
            location.append(name)
        else:
            location = ['0.0', '0.0', name]
    except Exception as e:
        print(e)
        location = ['0.0', '0.0', name]
    print(location)
    return location


get_location('浙江省')
get_location('杭州市')
get_location('上海市')
get_location('天津市')
get_location('安徽省')
get_location('合肥市') # 117.283042,31.86119

# ['120.153576', '30.287459', '浙江省']
# ['120.153576', '30.287459', '杭州市']
# ['121.472644', '31.231706', '上海市']
# ['117.190182', '39.125596', '天津市']
# ['117.283042', '31.861190', '安徽省']
# ['117.283042', '31.86119', '合肥市']

